<template>
	<view class="uni-container">
		<uni-forms ref="form" :model="formData" validateTrigger="bind">
			<uni-forms-item name="name" label-width="100" label="商户名称" required>
				<uni-easyinput placeholder="商户名称" v-model="formData.name"></uni-easyinput>
			</uni-forms-item>
			<uni-forms-item name="logo" label-width="100" label="商户LOGO">
				<!-- <uni-easyinput placeholder="商户LOGO" v-model="formData.logo"></uni-easyinput> -->
				<button @click="chooseLogoImage" size="mini">选择图片</button>
				<progress :percent="percent" show-info stroke-width="3" />
				<image v-if="formData.logo" :src="formData.logo" style="width: 100px; height: 100px;"></image>
			</uni-forms-item>
			<uni-forms-item name="contact" label="联系人">
				<uni-easyinput placeholder="联系人" v-model="formData.contact"></uni-easyinput>
			</uni-forms-item>
			<uni-forms-item name="email" label="邮箱">
				<uni-easyinput placeholder="邮箱" v-model="formData.email"></uni-easyinput>
			</uni-forms-item>
			<uni-forms-item name="phone" label="联系电话" required>
				<uni-easyinput placeholder="联系电话" v-model="formData.phone" ></uni-easyinput>
			</uni-forms-item>
			<uni-forms-item name="address" label="商户地址">
				<uni-easyinput placeholder="商户地址" v-model="formData.address"></uni-easyinput>
			</uni-forms-item>
			<uni-forms-item name="description" label="商户描述">
				<uni-easyinput placeholder="商户描述" v-model="formData.description"></uni-easyinput>
			</uni-forms-item>
			<uni-forms-item name="business_license_number" label="营业执照号码">
				<uni-easyinput placeholder="营业执照号码" v-model="formData.business_license_number"></uni-easyinput>
			</uni-forms-item>
			<uni-forms-item name="business_license" label="营业执照">
				<button @click="chooseLicenseImage" size="mini">选择图片</button>
				<progress :percent="percent" show-info stroke-width="3" />
				<image v-if="formData.business_license" :src="formData.business_license" style="width: 100px; height: 100px;"></image>
			</uni-forms-item>
			<uni-forms-item name="owner_id" label-width="100" label="商户管理员">
				<uni-easyinput placeholder="管理员" v-model="formData.ownername[0]" disabled></uni-easyinput>
			</uni-forms-item>
			<uni-forms-item name="rating" label="商户评分">
				<uni-rate v-model="formData.rating" :max="5" />
			</uni-forms-item>
			<uni-forms-item name="status" label-width="100" label="商户状态" required>
				<uni-data-checkbox v-model="formData.status"
					:localdata="formOptions.status_localdata"></uni-data-checkbox>
			</uni-forms-item>
			<uni-forms-item name="audit_status" label="审核状态">
				<uni-data-checkbox v-model="formData.audit_status" disabled
					:localdata="formOptions.audit_status_localdata"></uni-data-checkbox>
			</uni-forms-item>
			<view class="uni-button-group">
				<button type="primary" class="uni-button" style="width: 100px;" @click="submit">提交</button>
				<navigator open-type="navigateBack" style="margin-left: 15px;">
					<button class="uni-button" style="width: 100px;">返回</button>
				</navigator>
			</view>
		</uni-forms>
	</view>
</template>

<script>
	import {
		validator
	} from '../../js_sdk/validator/intangible_merchant.js';

	const db = uniCloud.database();
	const dbCmd = db.command;
	const dbCollectionName = 'intangible_merchant';

	function getValidator(fields) {
		let result = {}
		for (let key in validator) {
			if (fields.includes(key)) {
				result[key] = validator[key]
			}
		}
		return result
	}



	export default {
		data() {
			let formData = {
				"owner_id": "",
				"ownername": "",
				"name": "",
				"logo": "",
				"contact": "",
				"email": "",
				"address": "",
				"business_license": "",
				"business_license_number": "",
				"description": "",
				"phone": "",
				"rating": null,
				"status": 1
			}
			return {
				percent: 0, //图片上传进度条
				formData,
				formOptions: {
					"status_localdata": [{
							"text": "关闭",
							"value": 0
						},
						{
							"text": "营业中",
							"value": 1
						}
					],
					"audit_status_localdata": [{
							"text": "待审核",
							"value": 0
						},
						{
							"text": "已通过",
							"value": 1
						},
						{
							"text": "已拒绝",
							"value": 2
						}
					]
				},
				rules: {
					...getValidator(Object.keys(formData))
				}
			}
		},
		onLoad(e) {
			if (e.id) {
				const id = e.id
				this.formDataId = id
				this.getDetail(id)
			}
		},
		onReady() {
			this.$refs.form.setRules(this.rules)
		},
		methods: {
			chooseLogoImage() {
				const _self = this
				uniCloud.chooseAndUploadFile({
					type: 'image',
					count: 1,
					onChooseFile(res) {
						return Promise.all(res.tempFiles).then((fileList) => {
							let result = {
								tempFilePaths: []
							}
							result.tempFiles = fileList.map((fileItem, index) => {
								result.tempFilePaths.push(fileItem.path)
								// console.log(222222222222222,fileItem)
								return {
									path: fileItem.path,
									cloudPath: '' + Date.now() + index + '.' + fileItem.name.split(
										'.')[1], // 云端路径，这里随便生成了一个
									fileType: fileItem.fileType
								}
							})
							return result
						})
					},
					onUploadProgress(progressEvent) {
						console.log(progressEvent);
						_self.percent = Math.round((progressEvent.loaded * 100) / progressEvent.total);
					},
					success: async function(res) {
						// console.log(res)
						let temp = await uniCloud.getTempFileURL({
							fileList: res.tempFiles.map((item) => item.url)
						});
						// console.log(111111111111,temp)
						_self.formData.logo = temp.fileList[0].tempFileURL
						uni.showToast({
							icon: 'none',
							title: '上传成功',
							duration: 1500
						})
					},
					fail: function(err) {
						console.log(err)
						uni.showToast({
							icon: 'none',
							title: '上传失败',
							duration: 1500
						})
					}
				})
			},
			chooseLicenseImage() {
				const _self = this
				uniCloud.chooseAndUploadFile({
					type: 'image',
					count: 1,
					onChooseFile(res) {
						return Promise.all(res.tempFiles).then((fileList) => {
							let result = {
								tempFilePaths: []
							}
							result.tempFiles = fileList.map((fileItem, index) => {
								result.tempFilePaths.push(fileItem.path)
								// console.log(222222222222222,fileItem)
								return {
									path: fileItem.path,
									cloudPath: '' + Date.now() + index + '.' + fileItem.name.split(
										'.')[1], // 云端路径，这里随便生成了一个
									fileType: fileItem.fileType
								}
							})
							return result
						})
					},
					onUploadProgress(progressEvent) {
						console.log(progressEvent);
						_self.percent = Math.round((progressEvent.loaded * 100) / progressEvent.total);
					},
					success: async function(res) {
						// console.log(res)
						let temp = await uniCloud.getTempFileURL({
							fileList: res.tempFiles.map((item) => item.url)
						});
						// console.log(111111111111,temp)
						_self.formData.business_license = temp.fileList[0].tempFileURL
						uni.showToast({
							icon: 'none',
							title: '上传成功',
							duration: 1500
						})
					},
					fail: function(err) {
						console.log(err)
						uni.showToast({
							icon: 'none',
							title: '上传失败',
							duration: 1500
						})
					}
				})
			},
			/**
			 * 验证表单并提交
			 */
			submit() {
				uni.showLoading({
					mask: true
				})
				this.$refs.form.validate().then((res) => {
					// console.log(99999,res)
					res.owner_id = res.owner_id[0]
					return this.submitForm(res)
				}).catch(() => {}).finally(() => {
					uni.hideLoading()
				})
			},

			/**
			 * 提交表单
			 */
			submitForm(value) {
				// 使用 clientDB 提交数据
				return db.collection(dbCollectionName).doc(this.formDataId).update(value).then((res) => {
		
					uni.showToast({
						title: '修改成功'
					})
					this.getOpenerEventChannel().emit('refreshData')
					setTimeout(() => uni.navigateBack(), 500)
				}).catch((err) => {
					uni.showModal({
						content: err.message || '请求服务失败',
						showCancel: false
					})
				})
			},

			/**
			 * 获取表单数据
			 * @param {Object} id
			 */
			async getDetail(id) {
				uni.showLoading({
					mask: true
				})
				try {
					const users = db.collection("uni-id-users").field("_id,username").getTemp()
					const res = await db.collection(dbCollectionName, users).where("_id=='" + id + "'").field(
						"name,logo,contact,email,address,business_license,business_license_number,description,phone,rating,status,audit_status,owner_id._id as owner_id,owner_id.username as ownername"
					).get()
					// console.log(222222222222,res)
					const data = res.result.data[0]

					if (data) {
						this.formData = data
						console.log(this.formData)
						uni.hideLoading()
						return data
					}
				} catch (error) {
					uni.showModal({
						content: error.message || '请求服务失败',
						showCancel: false
					})
				}


			}

		}
	}
</script>